<template>
  <div class="order-confirm-container">
    <Header
      title="确认订单"
      :clickLeft="goBack"
    />
    <section class="address-container">
      <div class="head">
        <p class="title">{{form.shipment === 0 ? '订单配送至' : '到店自取'}}</p>
        <a href="javascript:;" class="btn" @click="isShowSelectType = true">重选配送方式</a>
      </div>
      <div class="body addr" v-if="form.shipment === 0" @click="selectAddress">
        <div class="text" v-if="address.Contact">
          <h1 class="name">
            {{address.Contact}}({{address.Gender}})
            <span>{{address.Mobile}}</span>
          </h1>
          <p class="address">{{address.Address + address.HouseNo}}</p>
        </div>
        <p class="noselect" v-else>请选择配送地址</p>
        <Icon name="arrow" class="arrow"></Icon>
      </div>
      <!-- <div class="body shop" v-else>
        <h1>{{storeData.Name}}</h1>
        <p>{{storeData.Address}}</p>
      </div> -->
    </section>
    <section class="main-contianer">
      <div class="shop-info">
        <img :src="storeData.Icon" alt>
        <p class="name">{{storeData.Name}}</p>
      </div>
      <div class="goods-list">
        <div class="item" v-for="item in cartData" :key="item.Id">
          <img :src="item.Image" alt>
          <p class="name">{{item.Name}}</p>
          <p class="num">x{{item.Num}}</p>
          <p class="price">
            <span>¥</span>{{(item.Num * item.Price).toFixed(2)}}
          </p>
        </div>
      </div>
      <Cell v-show="canDeliver" title="配送费" :value="`¥${preData.DeliverFee}`"/>
      <Cell
        v-show="!form.isBooking && preData.Manjian > 0"
        title="在线支付立减优惠"
        :value="`-¥${preData.Manjian}`"
        value-class="has-red"
      />
      <Cell
        v-show="!form.isBooking"
        @click="showCanUseRed"
        title="红包"
        :value-class="redText === '无可用红包' ? 'no-red' : 'has-red'"
        :value="redText"
        is-link
      />
      <Cell
        v-show="!preData.IsBooking"
        title="预计发货日期"
        :value="preData.BookingDate"
      />
      <div class="total-price">
        小计¥
        <span>
          {{canDeliver ? preData.ReceivableAmount.toFixed(2) : (preData.ReceivableAmount - preData.DeliverFee).toFixed(2)}}
        </span>
      </div>
      <p class="red-tip" v-show="preData.IsShowTip">使用红包时，实际支付金额小于1元的按1元支付。​​​</p>
    </section>
    <section class="other-container">
      <div class="pay-type">
        <p class="title">支付方式</p>
        <p class="value">
          <img class="pay-icon" src="../../assets/check.png">微信支付
        </p>
      </div>
      <div class="remark">
        <p class="title">订单备注</p>
        <div class="inputdiv">
          <input type="text" v-model="form.memo" placeholder="选填、可填写口味、偏好、包装要求">
        </div>
      </div>
    </section>
    <div class="footer">
      <p class="total-price">¥{{canDeliver ? preData.ReceivableAmount.toFixed(2) : (preData.ReceivableAmount - preData.DeliverFee).toFixed(2)}}</p>
      <Button type="primary" class="btn" :loading="loading" @click="confirm" :class="{'dis': !canDeliver && form.shipment === 0}">
        {{(canDeliver || form.shipment === 1) ? '确认支付' : `还差￥${storeData.DeliverMin - totalPrice}起送`}}
      </Button>
    </div>
    <Popup position="bottom" v-model="isShowSelectType" :overlay="false">
      <div class="van-dining-way-container dining-way-container">
        <div class="dining-way-head">请选择配送方式</div>
        <div class="dining-way-list">
          <div
            class="dining-way-item"
            :class="{'on': form.shipment === 0}"
            @click="form.shipment = 0"
          >
            <img class="dining-way-pic" src="../../assets/dining1.png">
            <div class="dining-way-info">
              <div class="dining-way-name">闪电配送</div>
              <div>Distribution</div>
            </div>
            <img class="dining-way-check" src="../../assets/gou.png">
          </div>
          <div
            class="dining-way-item"
            :class="{'on': form.shipment === 1}"
            @click="form.shipment = 1"
          >
            <img class="dining-way-pic" src="../../assets/dining2.png">
            <div class="dining-way-info">
              <div class="dining-way-name">到店自取</div>
              <div>Pick-up</div>
            </div>
            <img class="dining-way-check" src="../../assets/gou.png">
          </div>
        </div>
        <div class="button-bottom" @click="sureWay">确认</div>
      </div>
    </Popup>
    <Popup v-model="isShowCanUseRed" position="bottom">
      <div class="red-list">
        <div
          class="red-item"
          :class="{'selected': item.Id === form.couponId}"
          v-for="item in redList"
          :key="item.Id"
          @click="selectCoupon(item.Id)"
        >
          <RedItem :data="item" />
          <div class="red-img"></div>
          <img src="../../assets/selected.png" alt="">
        </div>
        <a href="javascript:;" class="cancel" @click="isShowCanUseRed = false">返回</a>
      </div>
    </Popup>
  </div>
</template>
<script>
import Header from "@/components/Header";
import RedItem from "@/components/RedItem";
import { Popup, Icon, Cell, Button, Toast, Dialog } from "vant";
import { clearCartData } from '../../utils/cart';
import appConfig from '../../config'
export default {
  components: {
    Header,
    Popup,
    Icon,
    Cell,
    Button,
    RedItem
  },
  data() {
    return {
      refreshLoading: false,
      storeId: 0,
      isShowSelectType: false,
      address: {},
      cartData: [],
      storeData: {},
      redList: [],
      redText: '',
      selectRedItem: {},
      loading: false,
      isShowCanUseRed: false,
      canDeliver: false,
      totalPrice: 0,
      preData: {
        CouponAmount: 0,
        DeliverFee: 0,
        Manjian: 0,
        OrderAmount: 0,
        ReceivableAmount: 0,
        IsShowTip: false
      },
      form: {
        addressId: 0,
        goodsJson: "",
        isBooking: false,
        shipment: 0,
        couponId: '',
        memo: ""
      }
    };
  },
  methods: {
    onRefresh() {
      setTimeout(() => {
        this.refreshLoading = false;
      }, 0);
    },
    selectCoupon(couponId) {
      if (couponId === this.form.couponId) {
        return;
      }
      this.form.couponId = couponId;
      this.getPrePrice().then(({ result }) => {
        this.preData = result;
        this.redText = this.getRedText();
      })
      this.isShowCanUseRed = false;
    },
    showCanUseRed() {
      if (this.redList.length === 0) return;
      this.isShowCanUseRed = true;
    },
    goBack() {
      this.$route.meta.notKeepAlive = true;
      this.$router.replace(`/shop/detail/${this.storeId}`);
    },
    getPrePrice() {
      const { form, storeId } = this;
      return this.$http.order.getPrePrice({
        ...form,
        storeId
      })
    },
    getRedText(redList = []) {
      const { preData } = this;
      if (preData.CouponAmount !== '--' && preData.CouponAmount !== 0) {
        return `-￥${preData.CouponAmount}`
      } else if (redList.length === 0) {
        return '无可用红包';
      } else {
        return `${redList.length}个可用`;
      }
    },
    getCanUseCoupon(goodsJson) {
      this.$http.order.getCanUseCoupon({
        goodsJson
      }).then(({ result }) => {
        this.redList = result;
        this.redText = this.getRedText(result);
      })
    },
    sureWay() {
      this.getPrePrice().then(({ result }) => {
        this.preData = result;
      });
      this.isShowSelectType = false;
    },
    selectAddress() {
      this.$router.push("/my/address?select=true");
    },
    getShopInfo() {
      return this.$http.order.storeInfo({
        storeId: this.storeId
      });
    },
    getCartData() {
      const cartData = this.$store.getters.cartData;
      let result = [];
      Object.keys(cartData).map(key => {
        result = result.concat(cartData[key]);
      });
      return result;
    },
    confirm() {
      if (this.preData.IsBooking) {
        Dialog.confirm({
          title: '提示',
          message: `该商品预计${this.preData.BookingDate}发货，是否继续付款？`
        }).then(() => {
          this.createOrder();
        })
      } else {
        this.createOrder();
      }
    },
    createOrder() {
      const { form, storeId } = this;
      this.loading = true;
      this.$http.order
        .create({
          storeId,
          ...form
        })
        .then(({ result }) => {
          clearCartData(this.storeId);
          this.createWxPay(result.no, result.type)
        })
        .catch((err) => {
          this.loading = false;
          Toast(err.msg);
        });
    },
    createWxPay(sourceNo, sourceType) {
      this.$http.pay
        .create({
          sourceNo,
          sourceType
        })
        .then(({ result }) => {
          this.loading = false;
          this.$http.pay.wxPay(result).then((res) => {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              Toast.success("支付成功！");
              this.$router.replace(`/order/detail/${sourceNo}`);
            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
              //支付过程中用户取消
              Toast.fail("取消支付");
              this.$router.replace(`/order/detail/${sourceNo}`);
            } else if (res.err_msg == "get_brand_wcpay_request:fail") {
              //支付失败
              Toast.fail(res.err_desc);
            }
          }).catch((err) => {
            this.loading = false;
            Toast.fail(err.msg);
            if (err.ok === 0) {
              this.$router.replace(`/order/detail/${sourceNo}`);
            }
          })
        }).catch((err) => {
          this.loading = false;
          Toast.fail(err.msg);
          if (err.ok === 0) {
            this.$router.replace(`/order/detail/${sourceNo}`);
          }
        })
    },
    getTotalPrice() {
      let totalPrice = 0;
      this.cartData.map(item => {
        totalPrice += item.Num * item.Price
      })
      return totalPrice.toFixed(2);
    }
  },
  created() {
    this.storeId = this.$route.params.id;
    this.cartData = this.getCartData();
    this.form.isBooking = this.cartData[0].Type === 'booking';
    this.totalPrice = this.getTotalPrice();
    this.form.goodsJson = JSON.stringify(
      this.cartData.map(item => ({ Id: item.Id, Count: item.Num }))
    );
    
    this.getShopInfo().then(({ result }) => {
      this.storeData = result;
      const address = this.$store.getters.address;
      if (address) {
        this.address = address;
        this.form.addressId = address.Id;
      } else {
        this.form.addressId = result.CustomerAddressId;
        this.address = {
          Address: result.CustomerAddress,
          AddressId: result.CustomerAddressId,
          Contact: result.CustomerContact,
          Gender: result.CustomerGender,
          HouseNo: result.CustomerHouseNo,
          Mobile: result.CustomerMobile
        };
      }
      
      this.canDeliver = this.totalPrice >= result.DeliverMin
      return this.getPrePrice();
    }).then(({ result }) => {
      this.preData = result;
      if (!this.form.isBooking) {
        this.getCanUseCoupon(this.form.goodsJson);
      }
    })
  },
  activated() {
    const address = this.$store.getters.address;
    if (address) {
      this.address = address;
      this.form.addressId = address.Id;
    }
  }
};
</script>
<style lang="less" scoped>
.order-confirm-container {
  padding-bottom: 110px;
  .van-dining-way-container{
    height: calc(100vh - 46px);
  }
  .dining-way-container {
    background-color: #fff;
    .dining-way-head {
      line-height: 60px;
      font-size: 30px;
      padding: 20px;
    }

    .dining-way-list {
      padding: 0 20px;
      overflow: hidden;
    }

    .dining-way-item {
      float: left;
      width: calc(50% - 24px);
      margin: 0 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 40px 0px;
      background: #f3f3f3;
      border-radius: 10px;
      position: relative;
      overflow: hidden;
      border: 2px solid #f3f3f3;
    }

    .dining-way-item.on {
      border: 2px solid #14a161;
      background: #fff;
    }

    .dining-way-pic {
      width: 100px;
      height: 100px;
      margin-right: 20px;
    }

    .dining-way-info {
      font-size: 24px;
      text-align: center;
    }

    .dining-way-name {
      font-size: 32px;
    }

    .dining-way-check {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 40px;
      height: 40px;
      opacity: 0;
    }

    .on .dining-way-check {
      opacity: 1;
    }
    .button-bottom {
      line-height: 80px;
      height: 80px;
      text-align: center;
      font-size: 30px;
      background: #14a161;
      color: #fff;
      margin: 40px 20px;
      border-radius: 10px;
    }
  }
  section {
    background-color: #fff;
    border-radius: 10px;
    margin: 20px 20px 0;
  }
  .address-container {
    .head {
      margin: 0 20px;
      padding: 20px 0;
      .border-bottom(#dedede);
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30px;
      .title {
        font-weight: bold;
      }
      .btn {
        color: @maincolor;
      }
    }
    .body {
      margin: 0 20px;
      padding: 20px 0;
      &.shop {
        h1 {
          margin-bottom: 10px;
          font-size: 30px;
        }
        p {
          font-size: 26px;
          color: #999;
        }
      }
      &.addr {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .text {
          font-size: 30px;
          h1 {
            margin-bottom: 10px;
          }
          p {
            color: #999;
          }
        }
        .noselect {
          font-size: 30px;
        }
        .arrow {
          font-size: 42px;
          color: #333;
        }
      }
    }
  }
  .main-contianer {
    padding: 0 20px;
    .no-red{
      color: #7f7f7f;
    }
    .has-red{
      color: red;
    }
    .shop-info {
      display: flex;
      align-items: center;
      padding: 20px 0;
      font-size: 30px;
      .border-bottom(#dedede);
      img {
        width: 60px;
        height: 60px;
        margin-right: 20px;
      }
    }
    .goods-list {
      .item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        img {
          width: 80px;
          height: 80px;
        }
        .name {
          width: calc(100% - 320px);
          font-size: 28px;
          margin-left: 20px;
          overflow : hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        .num,
        .price {
          text-align: right;
          font-size: 28px;
          margin-left: 20px;
          width: 70px;
        }
        .price {
          width: 150px;
          span {
            font-size: 24px;
          }
        }
      }
    }
  }
  .red-tip{
    padding-bottom: 20px;
    font-size: 24px;
    text-align: right;
    color: #999;
  }
  .total-price {
    text-align: right;
    line-height: 60px;
    padding: 20px 0;
    font-size: 30px;
    span {
      font-size: 36px;
    }
  }
  .other-container {
    padding: 0 20px;
    & > div {
      padding: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &:not(:last-child) {
        .border-bottom(#dedede);
      }
      .value {
        display: flex;
        align-items: center;
        .pay-icon {
          width: 36px;
          margin-right: 10px;
        }
      }
      .inputdiv {
        width: 500px;
        input {
          width: 100%;
          text-align: right;
        }
      }
    }
  }
  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 90px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 20px;
    box-sizing: border-box;
    background-color: #555;
    color: #fff;
    .total-price {
      font-size: 30px;
    }
    .btn {
      // width: 200px;
      height: 100%;
      background-color: @maincolor;
      &.dis{
        background-color: #7f7f7f;
        color: #fff;
        pointer-events: none;
      }
    }
  }
}
.red-list{
  background-color: #f3f4f5;
  padding: 20px 10px;
  .red-item{
    position: relative;
    margin-bottom: 20px;
    .red-img{
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0 0 100px 100px;
      border-color: transparent transparent #14a161 transparent;
      position: absolute;
      bottom: 0;
      right: 20px;
      display: none;
    }
    img{
      display: none;
      position: absolute;
      right: 30px;
      bottom: 10px;
      width: 48px;
      height: 48px;
    }
    &.selected{
      .red-img,
      img{
        display: block;
      }
    }
  }
  .cancel{
    height: 80px;
    margin: 20px 20px 0;
    font-size: 32px;
    background-color: #fff;
    text-align: center;
    line-height: 80px;
    display: block;
  }
}
</style>
<style lang="less">
.order-confirm-container {
  .van-cell {
    padding: 0.26667rem 0;
    &:after {
      left: 0;
    }
    .van-cell__title,
    .van-cell__value {
      font-size: 0.37333rem;
    }
    .van-cell__value {
      color: #333;
    }
  }
}
</style>
